package com.ccb.jyzx.expand.tiantouonline.job;

import com.alibaba.fastjson.JSON;
import com.ccb.jyzx.expand.tiantouonline.bean.FileInfo;
import com.ccb.jyzx.expand.tiantouonline.service.FileInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author XIEFEI
 * @date 2019-11-21 19:47
 * @Description 清理缓存文件
 **/
@Component
public class ClearCacheFileJob {
    Logger logger= LoggerFactory.getLogger(this.getClass());

    @Value("${file_cache_dir}")
    private String file_cache_dir;

    @Autowired
    FileInfoService fileInfoService;


    private static final SimpleDateFormat SF=new SimpleDateFormat("yyyyMMddHHmmss");

    private static final long CLEAR_NUM_LIMT=300;

    /**
     * 每3小时运行一次,清理fileInfo表里超过36小时还没上传的文件信息(upTag=0)以及缓存目录下对应的文件
     */
    @Scheduled(initialDelay = 1000L*60*20,fixedDelay=1000L*60*15)
    public void scheduled(){
        logger.info("===>开始清理缓存文件夹定时任务==>");
        AtomicInteger clearNum=new AtomicInteger(0);
        AtomicLong clearSize=new AtomicLong(0L);
        Calendar calendar=Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR,-36);
        Date time = calendar.getTime();
        Long topTime=Long.valueOf(SF.format(time));
        List<FileInfo> list =  fileInfoService.findByTimeTop(topTime,CLEAR_NUM_LIMT);
        list.forEach(clearFile->{
            String savePath = clearFile.getSavePath();
            File fileDir = new File(file_cache_dir,savePath);
            if(fileDir.exists()&&fileDir.isDirectory()){
                 Arrays.stream(fileDir.listFiles()).forEach(blockFile->{//删除文件夹下的所有块文件
                     clearSize.addAndGet(blockFile.length());
                     blockFile.delete();
                 });
                fileDir.delete();//删除文件夹
            }
            logger.info("===>开始清理缓存文件夹定时任务==>清理了文件fileId:"+clearFile.getId()+" 对应的存储文件"+savePath);
            //删除数据中信息
            fileInfoService.clearById(clearFile.getId());

            clearNum.getAndAdd(1);
        });

        long freeSpace = clearSize.get();
        double space = freeSpace/(1024.00*1024);
        String free = String.format("%.2f", space);
        logger.info("===>结束清理缓存文件夹定时任务==>共清理了"+clearNum.get()+"条记录 释放了"+free+" MB 的空间");
    }


}
